//
//  YZMBuyForDViewController.m
//  YZMicroStock
//
//  Created by apple on 17/6/22.
//  Copyright © 2017年 cqjr. All rights reserved.

#import "YZMBuyForDViewController.h"
#import "YZMWebViewService.h"
#import "NSNumber+Utils.h"
#import "YZClient.h"
#import "YZMRedPacketInfor.h"
#import "YZMStockViewController.h"
#import "YZMMyStackModel.h"
#import "YZMConfigureService.h"
#import "YZMStockRealModel.h"
#import "YZMAlertView.h"
#import "YZMBuyCountView.h"

@interface YZMBuyForDViewController ()<UITextFieldDelegate>
@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) UILabel *stockNameLB;
@property (nonatomic, strong) UITextField *amountTF;
@property (nonatomic, strong) UILabel *payMoneyLB;
@property (nonatomic, strong) UILabel *allMoneyLB;
@property (nonatomic, strong) UILabel *availMoneyLB;
@property (nonatomic, strong) UIView *redPacketView;
@property (nonatomic, strong) UILabel *redPacketLabel;
@property (nonatomic, strong) UIButton *expenseBtn;
@property (nonatomic, strong) UILabel *expenseLabel;
@property (nonatomic, strong) UIButton *buyBtn;
@property (nonatomic, strong) YZMRedPacketInfor *redpackModel;
@property (nonatomic, copy) NSString *stockCode;
@property (nonatomic, copy) NSString *stockName;
@property (nonatomic, strong) YZMMyStackModel *schemeModel;
@property (nonatomic, strong) YZMConfigureService *service;
@property (nonatomic, strong) YZMStockRealModel *stock;
//@property (nonatomic, strong) NSDate *stockFetchDate;
@property (nonatomic, strong) NSMutableDictionary *params;
@property (nonatomic, strong) NSTimer *timer;
@property (nonatomic, assign) NSInteger mount;

@end

@implementation YZMBuyForDViewController

- (NSMutableDictionary *)params {
    
    if (!_params) {
        
        _params = [NSMutableDictionary dictionary];
        _params[@"useTip"] = @(NO);
    }
    return _params;
}

- (instancetype)init{
    
    self = [super init];
    
    if (self) {
        
        self.title = @"T+D点买A股";
        self.service = [YZMTDConfigureService sharedService];
    }
    
    return self;
}


-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:YES];
    [self startTimer];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
    self.navigationItem.rightBarButtonItem = [YZMAppStyle rightBarItemWithTitle:@"规则" target:self action:@selector(rightBarItemPressed:)];
    
    [self createObject];
    [self fetchActivityRedPacketInfor];
}

-(void)createObject{
    
    WS(ws)
    self.scrollView = [[UIScrollView alloc] init];
    self.scrollView.showsVerticalScrollIndicator = NO;
    [self.view addSubview: self.scrollView];
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.edges.width.equalTo(ws.view);
    }];
    
    [self firstView];
}

-(void)firstView{
    
    WS(ws)
    UIView *firstView = [UIView new];
    firstView.backgroundColor = [YZMAppStyle colorForMain];
    [self.scrollView addSubview:firstView];
    [firstView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(ws.scrollView).offset(10);
        make.left.width.equalTo(ws.scrollView);
        make.height.mas_equalTo(151);
    }];
    
    UIView *nameView = [UIView new];
    nameView.backgroundColor = [YZMAppStyle colorForMain];
    [firstView addSubview:nameView];
    [nameView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.equalTo(firstView);
        make.height.mas_equalTo(50);
    }];
    
    UIView *priceView = [UIView new];
    priceView.backgroundColor = [YZMAppStyle colorForMain];
    [firstView addSubview:priceView];
    [priceView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.height.equalTo(nameView);
        make.top.equalTo(nameView.mas_bottom).offset(0.5);
    }];
    
    UIView *amountView = [UIView new];
    amountView.backgroundColor = [YZMAppStyle colorForMain];
    [firstView addSubview:amountView];
    [amountView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.height.equalTo(priceView);
        make.bottom.equalTo(firstView);
    }];
    
    UIView *line1 = [YZMAppStyle splitLine];
    [firstView addSubview:line1];
    [line1 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(firstView).offset(10);
        make.right.equalTo(firstView).offset(-10);
        make.top.equalTo(firstView).offset(50);
    }];
    
    UIView *line2 = [YZMAppStyle splitLine];
    [firstView addSubview:line2];
    [line2 mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.right.equalTo(line1);
        make.bottom.equalTo(firstView).offset(-50);
    }];
    
    UILabel *nameLB = [YZMAppStyle labelWithMediumWhite];
    [nameView addSubview:nameLB];
//    nameLB.text = @"股票名称";
    nameLB.text = [self.stockName stringByAppendingString:self.stockCode];
    [nameLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(nameView).offset(14);
        make.centerY.equalTo(nameView);
    }];
    
    self.stockNameLB = [YZMAppStyle labelWithMediumWhite];
    [nameView addSubview:self.stockNameLB];
//    self.stockNameLB.text = @"浩丰科技 SZ300419";
//    self.stockNameLB.text = [self.stockName stringByAppendingString:self.stockCode];
    self.stockNameLB.font = [YZMAppStyle fontWithSize:16];
    [self.stockNameLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(nameView);
        make.right.equalTo(nameView).offset(-16);
    }];
    
    UILabel *buyChargeLB = [YZMAppStyle labelWithMediumWhite];
    [priceView addSubview:buyChargeLB];
    buyChargeLB.text = @"买入价格";
    [buyChargeLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(nameLB);
        make.centerY.equalTo(priceView);
    }];
    
    UILabel *buyWayLB = [YZMAppStyle labelWithMediumLightGray];
    [priceView addSubview:buyWayLB];
    buyWayLB.text = @"市价委托";
    [buyWayLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(priceView);
        make.right.equalTo(priceView).offset(-16);
    }];
    
    UILabel *amountLB = [YZMAppStyle labelWithMediumWhite];
    [amountView addSubview:amountLB];
    amountLB.text = @"买入数量";
    [amountLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(amountView);
        make.left.equalTo(buyChargeLB);
    }];
    
    UILabel *labelInfo = [YZMAppStyle labelWithMediumLightGray];
    labelInfo.text = @"(必须为100的整数倍)";
    [amountView addSubview:labelInfo];
    [labelInfo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(amountView);
        make.left.equalTo(amountLB.mas_right).offset(15);
    }];
    
    UIButton *plusBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    plusBtn.tag = 1;
    plusBtn.hidden = YES;
    [plusBtn setImage:[UIImage imageNamed:@"icon_count_plus"] forState:UIControlStateNormal];
    [plusBtn setImage:[UIImage imageNamed:@"icon_count_plus_dis"] forState:UIControlStateDisabled];
    [plusBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [amountView addSubview:plusBtn];
    [plusBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(amountView).offset(-15);
        make.centerY.equalTo(amountView);
        make.width.height.mas_equalTo(24);
    }];
    
    UIButton *subBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    subBtn.tag = 2;
    subBtn.hidden = YES;
    subBtn.enabled = NO;
    [subBtn setImage:[UIImage imageNamed:@"icon_count_sub"] forState:UIControlStateNormal];
    [subBtn setImage:[UIImage imageNamed:@"icon_count_sub_dis"] forState:UIControlStateDisabled];
    [subBtn addTarget:self action:@selector(clickBtn:) forControlEvents:UIControlEventTouchUpInside];
    [amountView addSubview:subBtn];
    [subBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.right.equalTo(plusBtn.mas_right).offset(-104);
        make.centerY.equalTo(amountView);
        make.width.height.mas_equalTo(24);
    }];
    
    self.amountTF = [[UITextField alloc] init];
    self.amountTF.enabled = NO;
    self.amountTF.hidden = YES;
    self.amountTF.font = [YZMAppStyle largeSizeFont];
    self.amountTF.textColor = [YZMAppStyle colorForIconColor];
    self.amountTF.text = @"100";
    self.amountTF.textAlignment = NSTextAlignmentCenter;
    self.amountTF.delegate = self;
    self.amountTF.keyboardType = UIKeyboardTypeNumberPad;
    [amountView addSubview:self.amountTF];
    [self.amountTF mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(subBtn.mas_right);
        make.right.equalTo(plusBtn.mas_left);
        make.centerY.equalTo(amountView);
    }];

    YZMBuyCountView *buyView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([YZMBuyCountView class]) owner:self options:nil][0];
    buyView.tag = 11111;
    buyView.handle = ^(NSString *str) {
        ws.mount = [str integerValue];
    };
//    double maxAmonut = floor(self.schemeModel.availableMoney / [@(self.stock.price * self.service.defaultConfigure.tradingCountRatio).r2fString doubleValue] / 100) * 100;
//
//    if (![@(self.service.defaultConfigure.maxStockCount) isEqualGreaterThanDouble:maxAmonut]) {
//
//        maxAmonut = self.service.defaultConfigure.maxStockCount;
//    }
//
    double minAmonut = 100;
//    buyView.maxCount = maxAmonut;
    buyView.minCount = minAmonut;
    [self.scrollView addSubview:buyView];
    [buyView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(amountView);
        make.top.equalTo(amountView.mas_bottom);
        make.height.mas_equalTo(100);
    }];
    [self secondView:buyView];
   
}


-(void)secondView:(UIView *)topView{
    
    WS(ws)
    UIView *secondView = [UIView new];
    secondView.backgroundColor = [YZMAppStyle colorForMain];
    [self.scrollView addSubview:secondView];
    [secondView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(topView.mas_bottom).offset(14);
        make.left.right.with.equalTo(topView);
        make.height.mas_equalTo(102);
    }];
    
    UIView *payView = [UIView new];
    [secondView addSubview:payView];
    payView.backgroundColor = [YZMAppStyle colorForMain];
    [payView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.width.equalTo(secondView);
        make.height.mas_equalTo(50);
    }];
    
    UIView *line = [YZMAppStyle splitLine];
    [secondView addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(payView.mas_bottom);
        make.left.equalTo(payView).offset(10);
        make.right.equalTo(payView).offset(-10);
    }];
    
    UIView *availView = [UIView new];
    availView.backgroundColor = [YZMAppStyle colorForMain];
    [secondView addSubview:availView];
    [availView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(line.mas_bottom);
        make.left.right.width.equalTo(payView);
        make.height.mas_equalTo(60.5);
    }];
    
    UILabel *PayLB = [YZMAppStyle labelWithMediumWhite];
    PayLB.text = @"支付>交易综合费";
    [payView addSubview:PayLB];
    [PayLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(payView);
        make.left.equalTo(payView).offset(15);
    }];
    
    UILabel *labelPayMoneyInfo = [YZMAppStyle labelWithWhite];
    labelPayMoneyInfo.text = @"元";
    labelPayMoneyInfo.font = [YZMAppStyle smallSizeFont];
    [payView addSubview:labelPayMoneyInfo];
    [labelPayMoneyInfo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(PayLB);
        make.right.equalTo(payView).offset(-10);
    }];
    self.payMoneyLB = [YZMAppStyle labelWithMediumWhite];
    self.payMoneyLB.font = [YZMAppStyle largeSizeFont];
    self.payMoneyLB.textColor = [YZMAppStyle colorForIconColor];
    [payView addSubview:self.payMoneyLB];
    [self.payMoneyLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(PayLB);
        make.right.equalTo(labelPayMoneyInfo.mas_left).offset(-6);
    }];
    
    UILabel *allMoneyLB = [YZMAppStyle labelWithMediumWhite];
    allMoneyLB.text = @"占用点买金";
    [availView addSubview:allMoneyLB];
    [allMoneyLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(availView).offset(10.5);
        make.left.equalTo(PayLB);
    }];
    
    UILabel *labelAllMoneyInfo = [YZMAppStyle labelWithWhite];
    labelAllMoneyInfo.text = @"元";
    labelAllMoneyInfo.font = [YZMAppStyle smallSizeFont];
    [availView addSubview:labelAllMoneyInfo];
    [labelAllMoneyInfo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(allMoneyLB);
        make.right.equalTo(availView).offset(-10);
    }];
    
    self.allMoneyLB = [YZMAppStyle labelWithMediumWhite];
    self.allMoneyLB.font = [YZMAppStyle largeSizeFont];
    self.allMoneyLB.textColor = [YZMAppStyle colorForIconColor];
    [availView addSubview:self.allMoneyLB];
    [self.allMoneyLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(allMoneyLB);
        make.right.equalTo(labelAllMoneyInfo.mas_left).offset(-6);
    }];
    
    UILabel *availLB = [YZMAppStyle labelWithMediumLightGray];
    availLB.text = @"可用点买金";
    [availView addSubview:availLB];
    [availLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(allMoneyLB.mas_bottom).offset(6);
        make.left.equalTo(allMoneyLB);
    }];
    
    UILabel *labelAvailInfo = [YZMAppStyle labelWithWhite];
    labelAvailInfo.text = @"元";
    labelAvailInfo.font = [YZMAppStyle smallSizeFont];
    [availView addSubview:labelAvailInfo];
    [labelAvailInfo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(availLB);
        make.right.equalTo(availView).offset(-10);
    }];
    self.availMoneyLB = [YZMAppStyle labelWithMediumLightGray];
    self.availMoneyLB.font = [YZMAppStyle largeSizeFont];
    self.availMoneyLB.text = @(self.schemeModel.availableMoney).p02fString;
    [availView addSubview:self.availMoneyLB];
    [self.availMoneyLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.centerY.equalTo(availLB);
        make.right.equalTo(labelAvailInfo.mas_left).offset(-6);
    }];
    
    //是否使用红包
    self.redPacketView = [UIView new];
    [self.view addSubview:self.redPacketView];
    self.redPacketView.hidden = YES;
    self.redPacketView.backgroundColor = [YZMAppStyle colorForMain];
    [self.redPacketView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.height.mas_equalTo(56);
        make.left.right.width.equalTo(secondView);
        make.top.equalTo(secondView.mas_bottom).offset(15);
    }];
    
    UIView *redTopLine = [YZMAppStyle splitLine];
    [self.redPacketView addSubview:redTopLine];
    [redTopLine mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.left.right.equalTo(ws.redPacketView);
    }];
    
    UIView *redBottomLine = [YZMAppStyle splitLine];
    [self.redPacketView addSubview:redBottomLine];
    [redBottomLine mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.left.right.equalTo(ws.redPacketView);
    }];
    
    self.redPacketLabel = [YZMAppStyle labelWithSmallWhite];
    [self.redPacketView addSubview:self.redPacketLabel];
    [self.redPacketLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.equalTo(ws.redPacketView).offset(14);
        make.top.equalTo(ws.redPacketView).offset(13);
    }];
    
    UILabel *redPacketHintLB = [YZMAppStyle labelWithSmallLightGray];
    redPacketHintLB.text = @"红包余额只能抵扣交易综合费";
    [self.redPacketView addSubview:redPacketHintLB];
    [redPacketHintLB mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(ws.redPacketLabel.mas_bottom).offset(5);
        make.left.equalTo(ws.redPacketLabel);
    }];
    
    self.expenseLabel = [YZMAppStyle labelWithSmallWhite];
    [self.redPacketView addSubview:self.expenseLabel];
    [self.expenseLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.top.equalTo(ws.redPacketLabel.mas_bottom);
        make.right.equalTo(ws.redPacketView).offset(-15);;
    }];
    
    self.expenseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.expenseBtn setImage:[UIImage imageNamed:@"icon_redpacket_selected"] forState:UIControlStateNormal];
    [self.expenseBtn setImage:[UIImage imageNamed:@"icon_redpacket_unselected"] forState:UIControlStateSelected];
    [self.expenseBtn addTarget:self action:@selector(selectedExpense:) forControlEvents:UIControlEventTouchUpInside];
    [self.redPacketView addSubview:self.expenseBtn];
    
    [self.expenseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.height.width.mas_equalTo(12);
        make.centerY.equalTo(self.expenseLabel);
        make.right.equalTo(self.expenseLabel.mas_left).offset(-5);
    }];
    
    self.buyBtn = [YZMAppStyle submitButton];
    [self.buyBtn setTitle:@"提交" forState:UIControlStateNormal];
    self.buyBtn.enabled = YES;
    [self.view addSubview:self.buyBtn];
    [self.buyBtn addTarget:self action:@selector(submitBuy:) forControlEvents:UIControlEventTouchUpInside];
    [self.buyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.bottom.equalTo(ws.view).offset(-30);
        make.left.equalTo(ws.scrollView).offset(15);
        make.right.equalTo(ws.scrollView).offset(-15);
        make.width.mas_equalTo(ScreenWidth-30);
    }];
}

#pragma mark netWorking
-(void)fetchActivityRedPacketInfor{
    
    WS(ws)
    [YZClient Activity_RedpacketInforsuccess:^(NSURLSessionDataTask *task, id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
            ws.redpackModel = topModel.data;
            if ([@(ws.redpackModel.tipBalance) isGreaterThanDouble:0]) {
            
                ws.redPacketView.hidden = NO;
                self.redPacketLabel.text = [NSString stringWithFormat:@"是否使用红包余额（余额:%@元）", @(ws.redpackModel.tipBalance).r2fString];

                if ([@(ws.redpackModel.tipBalance) isEqualGreaterThanDouble:[ws.payMoneyLB.text doubleValue]]) {
                    
                    self.expenseLabel.text = [NSString stringWithFormat:@"-%@元",ws.payMoneyLB.text];
                } else {
                    
                    self.expenseLabel.text = [NSString stringWithFormat:@"-%@元", @(ws.redpackModel.tipBalance).r2fString];
                }
            }
        }else{
            
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
}

- (void)requestToLoadReal{
    
    __weak typeof(&*self) safeSelf = self;
    [YZClient qt_getRealtimeInfoWithStockCodes:@[self.stockCode] success:^(NSURLResponse *response, id responseObject) {
        
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            
//            [hud hide:YES];
            NSDictionary *dict = topModel.data;
            safeSelf.stock = dict[self.stockCode];
//            safeSelf.stockFetchDate = [NSDate date];
            double maxAmonut = floor(self.schemeModel.availableMoney / [@(self.stock.price * self.service.defaultConfigure.tradingCountRatio).r2fString doubleValue] / 100) * 100;
            
            if (![@(self.service.defaultConfigure.maxStockCount) isEqualGreaterThanDouble:maxAmonut]) {
                
                maxAmonut = self.service.defaultConfigure.maxStockCount;
            }
            YZMBuyCountView* buyView = [safeSelf.scrollView viewWithTag:11111];
            buyView.maxCount = maxAmonut < 100 ? 100 : maxAmonut;

            [self updateData];
        }else{
            
//            [hud hide:NO];
            [topModel showMessage];
        }
        
    } failure:^(NSError *error) {
        
//        [hud hide:NO];
        [error yz_showMessage];
    }];
}


- (void)updateData{
    //当前数量
    NSInteger amount = self.mount;
    
    //点买总金额
    CGFloat currentPrice = [@(self.stock.price * self.service.defaultConfigure.tradingCountRatio).r2fString doubleValue];
    
    double totalMoney = currentPrice > self.stock.limitUpPrice ? self.stock.limitUpPrice * amount : currentPrice * amount;
    
//    double totalMoney = currentPrice * amount;

    //交易综合费
    double charge = 0;
    if ([@(totalMoney) isEqualGreaterThanDouble:10000]) {
        
        charge = totalMoney / 10000 * self.service.defaultConfigure.serviceCharge;
    } else {
        
        charge = ceil(totalMoney / 10000) * self.service.defaultConfigure.serviceCharge;
    }
    
    self.payMoneyLB.text = @(charge).r2fString;
    self.allMoneyLB.text = @(totalMoney).r2fString;
    
    if ([@(self.redpackModel.tipBalance) isEqualGreaterThanDouble:[self.payMoneyLB.text doubleValue]]) {
        
        self.expenseLabel.text = [NSString stringWithFormat:@"-%@元",self.payMoneyLB.text];
    } else {
        
        self.expenseLabel.text = [NSString stringWithFormat:@"-%@元", @(self.redpackModel.tipBalance).r2fString];
    }
    
    self.params[@"chargePrice"] = self.payMoneyLB.text;
    self.params[@"money"] = self.allMoneyLB.text;
    _params[@"useTip"] = @(!self.expenseBtn.selected);
}

#pragma mark -- event

- (void)clickBtn:(UIButton *)sendr {
    
    UIButton *plusBtn = [self.view viewWithTag:1];
    UIButton *subBtn = [self.view viewWithTag:2];
    
    if (sendr.tag == 1) {
        
        subBtn.enabled = YES;
        double maxAmonut = floor(self.schemeModel.availableMoney / [@(self.stock.price * self.service.defaultConfigure.tradingCountRatio).r2fString doubleValue] / 100) * 100;
        
        if (![@(self.service.defaultConfigure.maxStockCount) isEqualGreaterThanDouble:maxAmonut]) {
        
            maxAmonut = self.service.defaultConfigure.maxStockCount;
        }
        NSNumber *currentAmount = @([self.amountTF.text integerValue] + 100);
        
        if (maxAmonut <= 0) {
            
            sendr.enabled = NO;
            return;
        }
    
        if ([currentAmount isEqualGreaterThanDouble:maxAmonut]) {
            
            self.amountTF.text = [NSString stringWithFormat:@"%@", @(maxAmonut).rfString];
            sendr.enabled = NO;
        } else {
            
            self.amountTF.text = [NSString stringWithFormat:@"%@", currentAmount];
        }
    } else {
        
        plusBtn.enabled = YES;
        double minAmonut = 100;
        NSNumber *currentAmount = @([self.amountTF.text integerValue] - 100);
        
        if (![currentAmount isGreaterThanDouble:minAmonut]) {
            
            self.amountTF.text = [NSString stringWithFormat:@"%@", @(minAmonut).rfString];
            sendr.enabled = NO;
        } else {
            self.amountTF.text = [NSString stringWithFormat:@"%@", currentAmount];
        }
    }
}

- (void)selectedExpense:(UIButton *)send {
    
    self.expenseBtn.selected = !self.expenseBtn.isSelected;
    _params[@"useTip"] = @(!send.selected);
}


-(void)submitBuy:(UIButton *)sender{
    
    if (kNetworkNotReachability) {
        [MBProgressHUD showMessage:@"网络无法连接，请联网后重试"];
        return;
    }
    
    
    self.params[@"useTip"] = @(!self.expenseBtn.selected);
    self.params[@"ID"] = @(self.schemeModel.Id);
    self.params[@"amount"] = @(self.mount).p0fString;
    self.params[@"stockCode"] = self.stockCode;
    
    double money;
    if (!self.expenseBtn.selected) {
        
        if ( [@(self.redpackModel.tipBalance) isEqualGreaterThanDouble:[self.params[@"chargePrice"] doubleValue]]) {
            money = [self.params[@"money"] doubleValue] - self.schemeModel.availableMoney;
        }else{
            
            money = [self.params[@"chargePrice"] doubleValue] + [self.params[@"money"] doubleValue] - ( self.redpackModel.tipBalance + self.schemeModel.availableMoney);
        }
    }else{

        money = [self.params[@"chargePrice"] doubleValue] + [self.params[@"money"] doubleValue] - self.schemeModel.availableMoney;
    }
    
    //余额判断
    if ( [@(money) isGreaterThanDouble:0.0] ) {
        //余额不足
        YZMAlertView *alertView = [[YZMAlertView alloc] init];
        alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
        alertView.contentLabel.text = [NSString stringWithFormat:@"策略组余额不足,您可以到“个人中心-我的策略组组”追加策略组点买金额"];
        alertView.cancelButton.hidden = YES;
        [alertView showInView:YZMHCMInstance.currentNavationCtroller.view];
        return;
    }

    //交易数量判断
    if ([self.params[@"amount"] integerValue] > self.service.defaultConfigure.maxStockCount) {

        YZMAlertView *alertView = [[YZMAlertView alloc] init];
        alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
        alertView.contentLabel.text = @"单只股票交易数量已达到上限";
        [alertView showInView:YZMHCMInstance.currentNavationCtroller.view];
        return;
    }

    //方案是否当天到期
    if (self.schemeModel.availableDays == 0) {

        YZMAlertView *alertView = [[YZMAlertView alloc] init];
        alertView.contentLabel.textAlignment = NSTextAlignmentCenter;
        alertView.contentLabel.text = [NSString stringWithFormat:@"您的T+D点买策略组即将到期，不允许买入！"];

        [alertView showInView:YZMHCMInstance.currentNavationCtroller.view];
        return;
    }
    
    //判断是否交易时段
    if (![[YZMConfigureService sharedServiceWithTradeType:YZM_TRADE_TYPE_FOR_A_STOCK_D] isInTradeTimePeriods]) {
        
        [[YZMAlertView alertViewForRecommandWithContent:@"当前为非点买时段，无法发起策略"] showInView:YZMHCMInstance.currentNavationCtroller.view];
        return;
    }
    
    //判断是否超过一分钟时长
//    if ([[NSDate date] timeIntervalSinceDate:self.stockFetchDate] >= 60) {
//        
//        YZMAlertView *alertView = [YZMAlertView alertViewForRecommandWithContent:@"超过一分钟，需重新获取股票价格后再重新发起"];
//        alertView.confirmHandle = ^{
//            
//            [self requestToLoadReal];
//            return YES;
//        };
//        [alertView showInView:self.navigationController.view];
//        return;
//    }

    MBProgressHUD *hud = [MBProgressHUD showProgressMessageManual:@"提交中"];
    [YZClient td_createStrategyWithParams:self.params success:^(NSURLSessionDataTask *task, id responseObject){

        YZGeneralResultModel *topModel=responseObject;
        [hud hide:YES];
        if (topModel.success) {

            [[NSNotificationCenter defaultCenter] postNotificationName:@"refreshScheme" object:nil];
            [MBProgressHUD showMessage:@"点买成功"];
            [YZMUserServiceInstance fetchUserAssetsInfo];
            UIViewController *viewController = [YZMHCMInstance instanceWithControllerName:@"stockTD"];
            if(viewController){

                YZMStockViewController *tradeVC = (YZMStockViewController *)viewController;
                [[NSNotificationCenter defaultCenter] postNotificationName:PopScrollNSNOtification object:nil];
                [tradeVC showSellListPage];
            }
            [YZMHCMInstance popViewController:nil animated:YES];

        }else{
            NSString *token = [topModel.data objectForKey:@"token"];
            if (token.length >0) {
                
                self.service.defaultConfigure.token = token;
            }
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        [hud hide:YES];
        [error yz_showMessage];
    }];
}

- (void)startTimer{
    
    if (self.timer == nil) {
        self.timer = [NSTimer timerWithTimeInterval: 1.0 target:self selector: @selector(requestToLoadReal) userInfo: nil repeats: YES];
        [[NSRunLoop mainRunLoop] addTimer: self.timer forMode: NSRunLoopCommonModes];
        [self.timer fire];
    }
}

- (void)stopTimer{
    
    if (self.timer) {
        
        [self.timer invalidate];
        self.timer = nil;
    }
}

-(void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    [self stopTimer];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)rightBarItemPressed:(id)sender{
    
    [YZMWebViewService openTradeRule:YZM_TRADE_TYPE_FOR_A_STOCK_D];
}

- (void)updateWithParams:(NSDictionary *)params {
    
    self.stockCode = params[@"stockCode"];
    self.stockName = params[@"stockName"];
    self.schemeModel = params[@"schemeModel"];
}

+ (instancetype)createWithParams:(NSDictionary *)params{
    
    YZMBuyForDViewController *ctrl = [[self alloc] init];
    [ctrl updateWithParams: params];
    return ctrl;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
